#ifndef _SERIAL_PROTO_H
#define _SERIAL_PROTO_H

#include "serial.h"
#include "controlstate.h"

class SerialProtocol : public SerialCommunication
{
public:
  static SerialProtocol *createInstance(char const*p_sDevice, long p_lBaud, void_function p_pFuncIncomingEvent, void_function p_pFuncStatusChanged);

  virtual ~SerialProtocol();

  int connect(bool p_bBlocking);
  void disconnect();
  inline bool isConnected() const
  {
    return m_bConnected;
  }

  bool addEvent(int p_iMajorID, int p_iMinorID, int p_iValue);

private:
  /** Must not be called. Bad, bad CTor!*/
  SerialProtocol();

  /** Hidden CTor.*/
  SerialProtocol(long p_lBaud);

  virtual void handleReceivedBytes();
  virtual void handleError(int p_iError, char const *p_sError);

  void controlThread(void);
  void parseHeader();
  void parseMessage();

  ControlState m_State;
  boost::thread *m_ptControl;
  boost::function<void (void)> m_funcIncoming;
  boost::function<void (void)> m_funcStatus;

  boost::condition m_cConnectionStateChanged;
  boost::condition m_condIncoming;
  boost::recursive_mutex m_syncWait;

  std::deque<unsigned char> m_dMessage;
  unsigned char m_iWaiting4Bytes;

  bool m_bAllowZeroInData;
  bool m_bConnected;
  bool m_bControlWantRun;
};

#endif
